<route>
{
    meta: {
        whiteList: true,
        title: "登录",
        constant: true,
        layout: false
    }
}
</route>

<script setup name="Login">
import { useI18n } from "vue-i18n";
import useSettingsStore from "@/store/modules/settings";
import useUserStore from "@/store/modules/user";
import storage from "@/utils/storage";
import { captchaImage } from "@/api/login";
import { onBeforeMount } from "vue";
import { TOKEN } from "@/store/mutation-types";

const route = useRoute();
const router = useRouter();

const settingsStore = useSettingsStore();
const userStore = useUserStore();

const { t } = useI18n();

const banner = new URL("../assets/images/login-banner.png", import.meta.url)
  .href;
const title = import.meta.env.VITE_APP_TITLE;

// 表单类型，login 登录，register 注册，reset 重置密码
const formType = ref("login");

// 登录
const captchaInfo = ref({
  img: undefined,
  uuid: undefined
});
const loginFormRef = ref();
const loginForm = ref({
  username: "admin",
  password: "admin123",
  code: undefined,
  uuid: undefined
});
const loginRules = ref({
  username: [{ required: true, trigger: "blur", message: "请输入用户名" }],
  code: [{ required: true, trigger: "blur", message: "请输入验证码" }],
  password: [
    { required: true, trigger: "blur", message: "请输入密码" },
    { min: 6, max: 18, trigger: "blur", message: "密码长度为6到18位" }
  ]
});
function handleLogin() {
  loginFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      userStore
        .login(loginForm.value)
        .then((res) => {
          loading.value = false;
          if (res.code == 200) {
            ElNotification({
              type: "success",
              title: "提示",
              dangerouslyUseHTMLString: true,
              message: `登陆成功，欢迎您！！`,
              position: "top-right",
              duration: 5000
            });
          } else {
            getCaptcha();
          }
          router.push(redirect.value);
        })
        .catch((e) => {
          console.log(e);
          loading.value = false;
        });
    }
  });
}

function handleMangeLogin(t) {
  loading.value = true;
  var params = { token: t };
  userStore
    .tokenlogin(params)
    .then((res) => {
      loading.value = false;
      if (res.code == 200) {
        ElNotification({
          type: "success",
          title: "提示",
          dangerouslyUseHTMLString: true,
          message: `登陆成功，欢迎您！！`,
          position: "top-right",
          duration: 5000
        });
      } else {
        getCaptcha();
      }
      router.push(redirect.value);
    })
    .catch((e) => {
      console.log(e);
      loading.value = false;
    });
}

// 注册
const registerFormRef = ref();
const registerForm = ref({
  username: "",

  password: "",
  checkPassword: ""
});
const registerRules = ref({
  username: [{ required: true, trigger: "blur", message: "请输入用户名" }],
  code: [{ required: true, trigger: "blur", message: "请输入验证码" }],
  password: [
    { required: true, trigger: "blur", message: "请输入密码" },
    { min: 6, max: 18, trigger: "blur", message: "密码长度为6到18位" }
  ],
  checkPassword: [
    { required: true, trigger: "blur", message: "请再次输入密码" },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      }
    }
  ]
});
function handleRegister() {
  ElMessage({
    message: "注册模块仅提供界面演示，无实际功能，需开发者自行扩展",
    type: "warning"
  });
  registerFormRef.value.validate((valid) => {
    if (valid) {
      // 这里编写业务代码
    }
  });
}

// 重置密码
const resetFormRef = ref();
const resetForm = ref({
  account: storage.local.get("login_account"),
  captcha: "",
  newPassword: ""
});
const resetRules = ref({
  username: [{ required: true, trigger: "blur", message: "请输入用户名" }],
  code: [{ required: true, trigger: "blur", message: "请输入验证码" }],
  newPassword: [
    { required: true, trigger: "blur", message: "请输入新密码" },
    { min: 6, max: 18, trigger: "blur", message: "密码长度为6到18位" }
  ]
});
function handleReset() {
  ElMessage({
    message: "重置密码仅提供界面演示，无实际功能，需开发者自行扩展",
    type: "info"
  });
  resetFormRef.value.validate((valid) => {
    if (valid) {
      // 这里编写业务代码
    }
  });
}

const loading = ref(false);
const passwordType = ref("password");
const redirect = ref(null);
const passwordRef = ref();

onMounted(() => {
  if (router.currentRoute.value.query.token) {
    // return false;

    handleMangeLogin(router.currentRoute.value.query.token);

    redirect.value = "dashboard";
  } else {
    redirect.value = route.query.redirect ?? "/";
  }
  window.addEventListener("keydown", keyDown);
  console.log("token", router.currentRoute.value.query.token);
});

onBeforeMount(() => {
  getCaptcha();
});
function keyDown(e) {
  // 回车则执行登录方法 enter键的ASCII是13
  if (e.keyCode == 13 || e.keyCode == 100) {
    handleLogin(); // 定义的登录方法
  }
}
function getCaptcha() {
  captchaImage().then((res) => {
    captchaInfo.value.img = "data:image/gif;base64," + res.img;
    loginForm.value.uuid = res.uuid;
  });
}
function showPassword() {
  passwordType.value = passwordType.value === "password" ? "" : "password";
  nextTick(() => {
    passwordRef.value.focus();
  });
}

function testAccount(account) {
  loginForm.value.username = account;
  loginForm.value.password = "admin123";
  handleLogin();
}
</script>

<template>
  <div>
    <div class="bg-banner" />
    <i18n-selector class="i18n-selector">
      <el-icon>
        <svg-icon name="i-ri:translate" />
      </el-icon>
    </i18n-selector>
    <div id="login-box">
      <div class="login-banner">
        <!-- <div class="logo" /> -->
        <!-- <img :src="banner" class="banner" /> -->
      </div>
      <el-form
        v-show="formType == 'login'"
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        autocomplete="on"
      >
        <div class="title-container">
          <h3 class="title">欢迎来到 {{ title }} !</h3>
        </div>
        <div>
          <el-form-item prop="username">
            <el-input
              ref="username"
              v-model="loginForm.username"
              :placeholder="t('app.account')"
              type="text"
              tabindex="1"
              autocomplete="on"
            >
              <template #prefix>
                <el-icon>
                  <svg-icon name="i-ri:user-3-fill" />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              ref="passwordRef"
              v-model="loginForm.password"
              :type="passwordType"
              :placeholder="t('app.password')"
              tabindex="2"
              autocomplete="on"
              @keyup.enter="handleLogin"
            >
              <template #prefix>
                <el-icon>
                  <svg-icon name="i-ri:lock-2-fill" />
                </el-icon>
              </template>
              <template #suffix>
                <el-icon @click="showPassword">
                  <svg-icon
                    :name="
                      passwordType === 'password'
                        ? 'i-ri:eye-close-line'
                        : 'i-ri:eye-line'
                    "
                  />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item prop="code">
                <el-input
                  ref="code"
                  v-model="loginForm.code"
                  :placeholder="t('app.captcha')"
                  tabindex="2"
                  autocomplete="on"
                >
                  <template #prefix>
                    <el-icon>
                      <svg-icon name="ep:bell-filled" />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4"><span /></el-col>
            <el-col :span="8">
              <img
                class="getCaptcha"
                :src="captchaInfo.img"
                @click="getCaptcha"
              />
            </el-col>
          </el-row>
        </div>
        <div class="flex-bar">
          <el-checkbox v-model="loginForm.remember"> 记住我 </el-checkbox>
          <!-- <el-link
            type="primary"
            :underline="false"
            @click="formType = 'reset'"
          >
            忘记密码了?
          </el-link> -->
        </div>
        <el-button
          :loading="loading"
          type="primary"
          size="large"
          style="width: 100%"
          @click.prevent="handleLogin"
          @keyup.enter="keyDown(e)"
        >
          {{ t("app.login") }}
        </el-button>
        <!-- <div class="sub-link">
          <span class="text">还没有帐号?</span>
          <el-link
            type="primary"
            :underline="false"
            @click="formType = 'register'"
          >
            创建新帐号
          </el-link>
        </div> -->
        <div
          style="
            margin-top: 20px;
            margin-bottom: -20px;
            height: 40px;
            text-align: center;
          "
        ></div>
      </el-form>
      <el-form
        v-show="formType == 'register'"
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        class="login-form"
        auto-complete="on"
      >
        <div class="title-container">
          <h3 class="title">探索从这里开始! 🚀</h3>
        </div>
        <div>
          <el-form-item prop="account">
            <el-input
              ref="name"
              v-model="registerForm.account"
              placeholder="用户名"
              tabindex="1"
              autocomplete="on"
            >
              <template #prefix>
                <el-icon>
                  <svg-icon name="i-ri:user-3-fill" />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="captcha">
            <el-input
              ref="captcha"
              v-model="registerForm.captcha"
              placeholder="验证码"
              tabindex="2"
              autocomplete="on"
            >
              <template #prefix>
                <el-icon>
                  <svg-icon name="i-ic:baseline-verified-user" />
                </el-icon>
              </template>
              <template #append>
                <el-button>发送验证码</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              ref="passwordRef"
              v-model="registerForm.password"
              :type="passwordType"
              placeholder="密码"
              tabindex="3"
              autocomplete="on"
            >
              <template #prefix>
                <el-icon>
                  <svg-icon name="i-ri:lock-2-fill" />
                </el-icon>
              </template>
              <template #suffix>
                <el-icon>
                  <svg-icon
                    :name="
                      passwordType === 'password'
                        ? 'i-ri:eye-close-line'
                        : 'i-ri:eye-line'
                    "
                  />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="checkPassword">
            <el-input
              ref="checkPassword"
              v-model="registerForm.checkPassword"
              :type="passwordType"
              placeholder="确认密码"
              tabindex="4"
              autocomplete="on"
            >
              <template #prefix>
                <el-icon>
                  <svg-icon name="i-ri:lock-2-fill" />
                </el-icon>
              </template>
              <template #suffix>
                <el-icon>
                  <svg-icon
                    :name="passwordType === 'password' ? 'eye' : 'eye-open'"
                    @click="showPassword"
                  />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
        </div>
        <el-button
          :loading="loading"
          type="primary"
          size="large"
          style="width: 100%; margin-top: 20px"
          @click.prevent="handleRegister"
        >
          注册
        </el-button>
        <div class="sub-link">
          <span class="text">已经有帐号?</span>
          <el-link
            type="primary"
            :underline="false"
            @click="formType = 'login'"
          >
            去登录
          </el-link>
        </div>
      </el-form>
      <el-form
        v-show="formType == 'reset'"
        ref="resetFormRef"
        :model="resetForm"
        :rules="resetRules"
        class="login-form"
        auto-complete="on"
      >
        <div class="title-container">
          <h3 class="title">忘记密码了? 🔒</h3>
        </div>
        <div>
          <el-form-item prop="account">
            <el-input
              ref="name"
              v-model="resetForm.account"
              :placeholder="t('app.account')"
              type="text"
              tabindex="1"
              autocomplete="on"
            >
              <template #prefix>
                <el-icon>
                  <svg-icon name="i-ri:user-3-fill" />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="captcha">
            <el-input
              ref="captcha"
              v-model="resetForm.captcha"
              :placeholder="t('app.captcha')"
              type="text"
              tabindex="2"
              autocomplete="on"
            >
              <template #prefix>
                <el-icon>
                  <svg-icon name="i-ic:baseline-verified-user" />
                </el-icon>
              </template>
              <template #append>
                <el-button>
                  {{ t("app.sendCaptcha") }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="newPassword">
            <el-input
              ref="newPasswordRef"
              v-model="resetForm.newPassword"
              :type="passwordType"
              :placeholder="t('app.newPassword')"
              tabindex="3"
              autocomplete="on"
            >
              <template #prefix>
                <el-icon>
                  <svg-icon name="i-ri:lock-2-fill" />
                </el-icon>
              </template>
              <template #suffix>
                <el-icon @click="showPassword">
                  <svg-icon
                    :name="
                      passwordType === 'password'
                        ? 'i-ri:eye-close-line'
                        : 'i-ri:eye-line'
                    "
                  />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
        </div>
        <el-button
          :loading="loading"
          type="primary"
          size="large"
          style="width: 100%; margin-top: 20px"
          @click.prevent="handleReset"
        >
          {{ t("app.check") }}
        </el-button>
        <div class="sub-link">
          <el-link
            type="primary"
            :underline="false"
            @click="formType = 'login'"
          >
            {{ t("app.goLogin") }}
          </el-link>
        </div>
      </el-form>
    </div>
    <Copyright v-if="settingsStore.copyright.enable" />
  </div>
</template>

<style lang="scss" scoped>
[data-mode="mobile"] {
  #login-box {
    position: relative;
    width: 100%;
    height: 100%;
    top: inherit;
    left: inherit;
    transform: translateX(0) translateY(0);
    flex-direction: column;
    justify-content: start;
    border-radius: 0;
    box-shadow: none;

    .login-banner {
      width: 100%;
      padding: 20px 0;

      .banner {
        position: relative;
        right: inherit;
        width: 100%;
        max-width: 375px;
        margin: 0 auto;
        display: inherit;
        top: inherit;
        transform: translateY(0);
      }
    }

    .login-form {
      width: 100%;
      min-height: auto;
      padding: 30px;
    }
  }

  .copyright {
    position: relative;
    bottom: 0;
    padding: 20px 0;
  }
}

:deep(input[type="password"]::-ms-reveal) {
  display: none;
}

:deep(.i18n-selector) {
  position: absolute;
  z-index: 1;
  top: 20px;
  right: 20px;
  cursor: pointer;
  font-size: 18px;
  color: var(--el-text-color-primary);
}

.bg-banner {
  position: fixed;
  z-index: 0;
  width: 100%;
  height: 100%;
  background: radial-gradient(
    circle at center,
    var(--g-app-bg),
    var(--g-main-bg)
  );
}

#login-box {
  display: flex;
  justify-content: space-between;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
  background-color: var(--g-app-bg);
  border-radius: 10px;
  overflow: hidden;
  box-shadow: var(--el-box-shadow);

  .login-banner {
    position: relative;
    width: 450px;
    // background-color: var(--g-main-bg);
    background: url("../assets/images/login.png") no-repeat;
    overflow: hidden;

    .banner {
      width: 100%;

      @include position-center(y);
    }

    .logo {
      position: absolute;
      top: 20px;
      left: 20px;
      width: 30px;
      height: 30px;
      border-radius: 4px;
      background: url("../assets/images/logo.png") no-repeat;
      background-size: contain;
      box-shadow: var(--el-box-shadow-light);
    }
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 48px;
  }

  .login-form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    min-height: 500px;
    width: 500px;
    padding: 50px;
    overflow: hidden;

    .title-container {
      position: relative;

      .title {
        font-size: 1.3em;
        color: var(--el-text-color-primary);
        margin: 0 auto 30px;
        font-weight: bold;
      }
    }
  }

  .el-form-item {
    margin-bottom: 24px;

    :deep(.el-input) {
      height: 48px;
      line-height: inherit;
      width: 100%;

      input {
        height: 48px;
      }

      .el-input__prefix,
      .el-input__suffix {
        display: flex;
        align-items: center;
      }

      .el-input__prefix {
        left: 10px;
      }

      .el-input__suffix {
        right: 10px;
      }
    }
  }

  :deep(.el-divider__text) {
    background-color: var(--g-app-bg);
  }

  .flex-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
  }

  .sub-link {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 20px;
    font-size: 14px;
    color: var(--el-text-color-secondary);

    .text {
      margin-right: 10px;
    }
  }
}

.copyright {
  position: absolute;
  bottom: 30px;
  width: 100%;
  margin: 0;
}
</style>
